﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.IO;
using System.Configuration;
using VPIC_EDILib;
using System.Xml.Linq;
using System.Reflection;
using System.Timers;
namespace VPIC_EDIWS
{
    public partial class EDIService : ServiceBase
    {
        Timer timer1 = new Timer();
        public EDIService()
        {
            InitializeComponent();
        }
        public Config LoadConfig()
        {

            XElement elementRoot = XElement.Load(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\DBConfig.xml");
             
            Config config = (from q in elementRoot.Elements("Config")
                             select new Config
                             {
                                 ServerName = q.Element("ServerName").Value,
                                 DBName = q.Element("DBName").Value,
                                 ShareFolderCSV = q.Element("ShareFolderCSV").Value,
                                 ShareFolderXML = q.Element("ShareFolderXML").Value

                             }).First();
            
            return config;
        }
        protected override void OnStart(string[] args)
        {


            timer1.Elapsed += new ElapsedEventHandler(timer1_Elapsed);
            timer1.Interval = 5000;
            timer1.Enabled = true;
            timer1.Start();
          
          
        }

        protected override void OnStop()
        {
            timer1.Enabled = false;
        }
        private void Writelog(string message)
        {
            FileInfo fileLog = new FileInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\log.txt");
      
            if (fileLog.Exists)
            {
                StreamWriter writer = fileLog.AppendText();
                writer.WriteLine(message);
                writer.Flush();
                writer.Close();
            }
            else
            {
                StreamWriter writer = fileLog.CreateText();
                writer.WriteLine(message);
                writer.Flush();
                writer.Close();

            }
            

        }
        public void StartProcessImportInvoice(string filexml,string conn)
        {
            Writelog(conn);
            ProcessStartInfo Proc = new ProcessStartInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\ASImport.exe");
           
            Writelog(Proc.FileName);
            Proc.Arguments = conn;
            Proc.UseShellExecute = false;
            Proc.RedirectStandardError = true;
          
           
          
            Proc.RedirectStandardInput = true;
            Proc.RedirectStandardOutput = true;
            Proc.CreateNoWindow = false;
            Proc.ErrorDialog = false;
            Proc.WindowStyle = ProcessWindowStyle.Hidden;
            Proc.Verb = "runas";
            Writelog("Start Process ASImport");
            Process process = Process.Start(Proc);

            process.WaitForExit();
            process.Close();
            Writelog(Proc.FileName + " " + Proc.Arguments);
           
        }

        private void timer1_Elapsed(object sender, EventArgs e)
        {
            try
            {
                //args 0 : Export file 830 forecast , 1:862 Shipping Schedules
                Config itemConfig = new Config();

                itemConfig = this.LoadConfig();
                Writelog(itemConfig.ServerName);
                DirectoryInfo dirInfo = new DirectoryInfo(itemConfig.ShareFolderCSV);
                foreach (FileInfo fileEDI in dirInfo.GetFiles())
                {

                    Writelog(fileEDI.FullName);
                    while (fileEDI.IsReadOnly)
                    {

                    }
                    string type = "";
                    StreamReader ediReader = fileEDI.OpenText();
                    int i = 0;
                    while (ediReader.Peek() > 0)
                    {
                        if (i > 0)
                        {

                            string line = ediReader.ReadLine();
                            string[] tokens = line.Split(new char[1] { ',' });
                            type = tokens[0];
                        }
                        i++;

                    }
                    ediReader.Close();
                    XMLProcess XMLProcess = new XMLProcess(itemConfig);


                    if (type == "830")
                    {
                        List<EDIEntity> ListEDI = new List<EDIEntity>();
                        ListEDI = XMLProcess.GetListEDIEntitySOForecast(fileEDI);
                        string filename = XMLProcess.GetXMLSOForecast(ListEDI);
                        Writelog(filename);
                        Writelog("Start import");
                        StartProcessImportInvoice(filename, XMLProcess.GetProcessArg(filename));
                       
                        fileEDI.MoveTo(dirInfo.FullName + "\\Imported\\" + fileEDI.Name + DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss"));
                    }
                    if (type == "862")
                    {
                        List<EDIEntityShip> ListEDI = new List<EDIEntityShip>();
                        ListEDI = XMLProcess.GetListEDIEntitySOShip(fileEDI);
                        string filename = XMLProcess.GetXMLSOShippingSchedules(ListEDI);
                        Writelog(filename);
                        Writelog("Start import");
                        StartProcessImportInvoice(filename, XMLProcess.GetProcessArg(filename));
                        fileEDI.MoveTo(dirInfo.FullName + "\\Imported\\" + fileEDI.Name + DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss"));
                    }

                }
            }
            catch (Exception ex)
            {
                Writelog(ex.Message);
            }
         
        }
    }
}
